﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
using System.Threading;
using System.Diagnostics;
using System.IO;

namespace asfbinScript
{
    class wmv2avi
    {        
        private string m_wmvRoot;
        private string m_aviPath;
        private string m_mencodePath;

        private Process m_process;

        public delegate void OutputHandler(object sender, DataReceivedEventArgs e);
        private OutputHandler m_outputHandler;

        public wmv2avi(string wmvRoot, string aviPath, OutputHandler outputHandler)
        {
            m_wmvRoot = wmvRoot;
            m_aviPath = aviPath;
            m_process = null;
            m_mencodePath = @"d:\app\mplayer\mencoder.exe";
            m_outputHandler = outputHandler;
        }

        public void Convert(string wmvName)
        {
            // output avi
            string aviName = Path.Combine(m_aviPath, wmvSegments.wmvCut.getFileNameNoExt(wmvName)) + ".avi";

            // create process
            string argument = wmvName + " -oac copy -ovc copy -cache 8192 -ofps 100.0 -o " + aviName;

            Process p = new Process();
            p.StartInfo.FileName = m_mencodePath;
            p.StartInfo.Arguments = argument;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            // Set event handler
            p.OutputDataReceived += (s, e) =>
            {
                m_outputHandler(s, e);
            };                

            //execute the command
            p.Start();
            p.BeginOutputReadLine();
            //p.WaitForExit();
            //p.Close();
            m_process = p;
        }

        public void stop()
        {
            if (m_process != null)
            {
                m_process.Kill();
                m_process = null;
            }
        }

        public bool finish()
        {
            if (m_process != null)
            {
                return m_process.HasExited;
            }
            return true;
        }

    }
}
